package com.ls.bio;



import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO blocking IO
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {
        //思路
        //创建一个线程池
        //如果有客户端连接，就创建一个线程，与之通讯（单独写一个方法）

        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");

        while (true) {
            //监听等待客户端连接
            final Socket socket = serverSocket.accept();//阻塞
            System.out.println("连接到一个客户端");
            newCachedThreadPool.execute(() -> handler(socket));
        }
    }

    //和客户端通讯
    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        System.out.println("线程信息 id："+Thread.currentThread().getId());
        System.out.println("线程信息 name："+Thread.currentThread().getName());

        try (InputStream inputStream = socket.getInputStream()) {
            while (true) {
                int read = inputStream.read(bytes);//阻塞
                if (read != -1) {
                    String string = new String(bytes, 0, read);
                    System.out.println(string);
                } else {
                    System.out.println("退出");
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
